export function compressAccurately(file, config) {
  let files
  let fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2)
  const read = new FileReader()
  read.readAsDataURL(file)
  return new Promise(function (resolve) {
    read.onload = function (e) {
      let img = new Image()
      img.src = e.target.result
      img.onload = function () {
        console.log(this.width, this.height)
        // 默认按比例压缩
        const { w, h } = changeRatio(this, config)

        // 生成canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let base64
        // 创建属性节点
        canvas.setAttribute('width', w)
        canvas.setAttribute('height', h)
        ctx.drawImage(this, 0, 0, w, h)

        if (fileSize < 1) {
          //如果图片小于1M 那么不执行压缩操作
          base64 = canvas.toDataURL(file['type'], config.quality || 1)
        } else if (fileSize > 1 && fileSize < 2) {
          //如果图片大于1M并且小于2M 那么压缩0.5
          base64 = canvas.toDataURL(file['type'], 0.8);
        } else {
          //如果图片超过2m 那么压缩0.2
          base64 = canvas.toDataURL(file['type'], 0.5);
        }
        // 回调函数返回file的值（将base64编码转成file）
        files = dataURLtoFile(base64, file['name'])
        resolve(files)
      }
    }
  })
};

// base64转码（将base64编码转回file文件）
function dataURLtoFile(dataurl, fileName) {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}

// 设置图片比例
function changeRatio(img, config) {
  let w = img.width;
  let h = img.height;
  // 图片比例
  let ratio = img.width / img.height
  if (config.width && !config.height) {
    w = config.width;
    h = w / ratio;
  } else if (!config.width && config.height) {
    h = config.height;
    w = h * ratio;
  } else if (config.width && config.height) {
    w = config.width;
    h = config.height;
  }
  return {
    w: w,
    h: h
  }
}
